<template>
    <view class="container">
        <uni-forms ref="form" :label-width="100" :model="formData" :rules="rules">
            <!-- 商品名称 -->
            <uni-forms-item label="商品名称" required name="name">
                <uni-easyinput type="text" v-model="formData.name" placeholder="请输入商品名称" />
            </uni-forms-item>

            <!-- 价格 -->
            <uni-forms-item class="row-item" required label="商品价格" name="price">
                <uni-easyinput type="number" v-model="formData.price" placeholder="0.00">
                    <template #right>
                        <text>元</text>
                    </template>
                </uni-easyinput>
            </uni-forms-item>

            <!-- 折扣 -->
            <uni-forms-item class="row-item" required label="折扣比例" name="discount">
                <uni-easyinput type="number" v-model="formData.discount" placeholder="1-100">
                    <template #right>
                        <text>%</text>
                    </template>
                </uni-easyinput>
            </uni-forms-item>

            <!-- 抵扣 -->
            <uni-forms-item class="row-item" required label="抵扣金额" name="deduction">
                <uni-easyinput type="number" v-model="formData.deduction" placeholder="0.00">
                    <template #right>
                        <text>元</text>
                    </template>
                </uni-easyinput>
            </uni-forms-item>

            <!-- 库存 -->
            <uni-forms-item class="row-item" required label="商品库存" name="stockQuantity">
                <uni-easyinput type="number" v-model="formData.stockQuantity" placeholder="请输入库存" />
            </uni-forms-item>

            <!-- 商品描述 -->
            <uni-forms-item label="商品描述" required name="description">
                <uni-easyinput type="textarea" v-model="formData.description" placeholder="请输入商品描述（最多1000汉字）"
                    :maxlength="1000" autoHeight />
            </uni-forms-item>

            <!-- 类别选择 -->
            <uni-forms-item label="商品类别" required name="category">
                <uni-data-select v-model="formData.category" placement="top" :localdata="categoryOptions"
                    placeholder="请选择商品类别" />
            </uni-forms-item>

            <!-- 图片上传 -->
            <template v-if="formData.category==='car_services'||formData.category==='sys_car_supplies'">
                <uni-forms-item label="商品图片" required name="imageFileList">
                    <uni-file-picker :v-model="formData.imageFileList" :auto-upload="false" file-mediatype="image"
                        mode="grid" :limit="10" :image-styles="imageStyles" @select="selectImage" />
                </uni-forms-item>
            </template>

            <template v-if="formData.category==='car_services'">

                <!-- 服务类型 -->
                <uni-forms-item label="服务类型" required name="serviceType">
                    <tree-selector :value="formData.serviceType" node-key="id"
                        :props="{value:'id',label:'value',children:'dictionarys'}" placement="top" :data="serviceTypes"
                        @node-click="d=>formData.serviceType=d" placeholder="请选择汽车服务类型" />
                </uni-forms-item>
                <!-- 是否需要预约 -->
                <uni-forms-item label="是否需要预约" required name="appointmentRequired">
                    <radio-group @change="appointmentRequiredChange">
                        <radio label="1" :value="1">需要预约</radio>
                        <radio label="0" :value="0">无需预约</radio>
                    </radio-group>
                </uni-forms-item>

                <!-- 服务时长 -->
                <uni-forms-item label="服务时长" required name="duration">
                    <uni-easyinput v-model="formData.duration" placeholder="请输入时长（格式：小时:分钟 如 01:30）" />
                </uni-forms-item>

                <!-- 服务区域 -->
                <uni-forms-item label="服务区域" required name="serviceArea">
                    <uni-easyinput v-model="formData.serviceArea" placeholder="请输入服务区域" />
                </uni-forms-item>
            </template>
            <template v-if="formData.category==='sys_car_supplies'">
                <!-- 商品品牌选择 -->
                <uni-forms-item label="商品品牌" required name="brand">
                    <uni-data-select :trim="true" v-model="formData.brand" placement="top"
                        :localdata="brandOptions.map(d=>{return{value:d.id,text:d.value}})" placeholder="请选择商品品牌" />
                </uni-forms-item>
                <!-- 汽车用品类别选择 -->
                <uni-forms-item label="汽车用品类别" required name="carSuppliesCategory">
                    <tree-selector :value="formData.carSuppliesCategory" node-key="id"
                        :props="{value:'id',label:'value',children:'dictionarys'}" placement="top"
                        :data="carSuppliesCategoryOptions" @node-click="d=>formData.carSuppliesCategory=d"
                        placeholder="请选择汽车用品类别" />
                </uni-forms-item>
                <!-- 颜色 -->
                <uni-forms-item class="row-item" required label="颜色" name="color">
                    <uni-easyinput v-model="formData.color" placeholder="请输入颜色" />
                </uni-forms-item>
                <!-- 重量 -->
                <uni-forms-item class="row-item" required label="重量" name="weight">
                    <uni-easyinput :trim="true" v-model="formData.weight" placeholder="请输入重量" />
                </uni-forms-item>
                <!-- 尺寸 -->
                <uni-forms-item class="row-item" required label="尺寸" name="dimension">
                    <uni-easyinput :trim="true" v-model="formData.dimension" placeholder="请输入尺寸" />
                </uni-forms-item>
                <!-- 备注 -->
                <uni-forms-item label="备注" name="markUp">
                    <uni-easyinput type="textarea" :trim="true" v-model="formData.markUp" placeholder="请输入备注（最多250汉字）"
                        :maxlength="250" autoHeight />
                </uni-forms-item>
            </template>
            <template v-if="formData.category==='sys_vip_packages'">
                <!-- 会员选择 -->
                <uni-forms-item label="会员" required name="VIPId">
                    <uni-data-select v-model="formData.VIPId" :localdata="vipOptions.map(d=>{return{value:d.id,text:d.name};})" placeholder="请选择会员等级" />
                </uni-forms-item>

                <!-- 年份输入 -->
                <uni-forms-item label="年数" required name="year">
                    <uni-easyinput v-model="formData.year" type="number" placeholder="请输入年数（如：1）" />
                </uni-forms-item>

                <!-- 月份输入 -->
                <uni-forms-item label="月数" required name="month">
                    <uni-easyinput v-model="formData.month" type="number" placeholder="请输入月数（0-12）" />
                </uni-forms-item>
            </template>
			<button type="primary" @click="submitForm" class="submit-btn">保存</button>
        </uni-forms>
    </view>
</template>

<script>
    import {
        getProductBrand,
        getProductCategory,
        getCarSuppliesCategory,
        getCarServicesType,
        addCarSupplies,
        addCarServices,
        addVipPackages,
        getVipPackageVip
    } from '../apis/product'
	import {get_qcd_product} from '../apis/login.js'
    import treeSelector from '../components/treeSelector.vue'
    import {
        getUserInfo
    } from '../tools/cookieMgr'
    import {
        isLogin
    } from '../tools/tools'
    export default {
        components: {
            treeSelector
        },
        data() {
            return {
                formData: {
                    name: '',
                    category: '',
                    brand: '',
                    price: null,
                    discount: 100,
                    deduction: 0,
                    description: '',
                    stockQuantity: 0,
                    imageFileList: [],
                },
				id:'',
                categoryOptions: [], // 商品类别数据
                brandOptions: [], // 从字典表获取的品牌数据
                carSuppliesCategoryOptions: [], //从字典表获取的汽车用品类别数据
                serviceTypes: [], // 从字典表获取的服务类别数据
                vipOptions:[],// 从vip表获取的vip选择数据
                imageStyles: {
                    width: 200,
                    height: 200,
                    border: {
                        color: '#ddd',
                        width: 1,
                        style: 'dashed'
                    }
                },
                rules: {
                    name: {
                        rules: [{
                                required: true,
                                errorMessage: '商品名称不能为空'
                            },
                            {
                                minLength: 2,
                                maxLength: 25,
                                errorMessage: '名称长度2-25个字符'
                            }
                        ]
                    },
                    category: {
                        rules: [{
                            required: true,
                            errorMessage: '请选择商品类别'
                        }]
                    },
                    price: {
                        rules: [{
                                required: true,
                                errorMessage: '请输入商品价格'
                            },
                            {
                                validateFunction: function(rule, value, data, callback) {
                                    if (parseFloat(value) < 0.01) {
                                        return false
                                    }
                                    return true
                                },
                                errorMessage: "商品价格不能小于0.01"
                            }
                        ]
                    },
                    discount: {
                        rules: [{
                            validateFunction: function(rule, value, data, callback) {
                                if (parseInt(value) < 1||parseInt(value)>100) {
                                    return false
                                }
                                return true
                            },
                            errorMessage: '折扣范围1-100'
                        }]
                    },
                    deduction: {
                        rules: [{
                            validateFunction: function(rule, value, data, callback) {
                                if (parseFloat(value)<0) {
                                    return false
                                }
                                return true
                            },
                            errorMessage: '抵扣金额不能为负数'
                        }, ]
                    },
                    description: {
                        rules: [{
                                required: true,
                                errorMessage: '请填写商品描述'
                            },
                            {
                                maxLength: 1000,
                                errorMessage: '描述最多1000个汉字'
                            }
                        ]
                    },
                    stockQuantity: {
                        rules: [{
                                required: true,
                                errorMessage: '请填写库存数量'
                            },
                            {
                                validateFunction: function(rule, value, data, callback) {
                                    if (parseInt(value)<0) {
                                        return false
                                    }
                                    return true
                                },
                                errorMessage: '库存不能为负数'
                            }
                        ]
                    }
                }
            }
        },
        watch: {
            "formData.category": (function(newV) {
                var newRules = null;
                switch (newV) {
                    case "sys_car_supplies":
                        newRules = {
                            brand: {
                                rules: [{
                                    required: true,
                                    errorMessage: "请选择品牌"
                                }, ]
                            },
                            carSuppliesCategory: {
                                rules: [{
                                    required: true,
                                    errorMessage: "请选择汽车用品类别"
                                }, ]
                            },
                            color: {
                                rules: [{
                                    required: true,
                                    errorMessage: "请输入颜色"
                                }, ]
                            },
                            weight: {
                                rules: [{
                                    required: true,
                                    errorMessage: "请输入重量"
                                }, ]
                            },
                            dimension: {
                                rules: [{
                                    required: true,
                                    errorMessage: "请输入尺寸"
                                }, ]
                            }
                        }
                        break;
                    case "car_services":
                        newRules = {
                            serviceType: {
                                rules: [{
                                    required: true,
                                    errorMessage: '请选择服务类型'
                                }]
                            },
                            appointmentRequired: {
                                rules: [{
                                    required: true,
                                    errorMessage: '请选择是否需要预约'
                                }]
                            },
                            duration: {
                                rules: [{
                                        required: true,
                                        errorMessage: '请输入服务时长'
                                    },
                                    {
                                        format: 'string',
                                        pattern: /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/,
                                        errorMessage: '格式不正确（正确示例：01:30）'
                                    }
                                ]
                            },
                            serviceArea: {
                                rules: [{
                                    required: true,
                                    errorMessage: '请输入服务区域'
                                }]
                            }
                        }
                        break;
                    case "sys_vip_packages":
                        newRules = {
                            VIPId: {
                                rules: [{
                                    required: true,
                                    errorMessage: '请选择会员等级'
                                }]
                            },
                            year: {
                                rules: [{
                                        required: true,
                                        errorMessage: '年份不能为空'
                                    },
                                    {
                                        format: 'number',
                                        errorMessage: '请输入有效的年数'
                                    }, {
                                        validateFunction: (a, value) => {
                                            if (parseInt(value) < 0) {
                                                return false;
                                            }
                                            return true;
                                        },
                                        errorMessage: "年数不能为负数"
                                    }, {
                                        validateFunction: (a, value, data) => {
                                            if (value === 0 && data.month === 0) {
                                                return false;
                                            }
                                            return true;
                                        },
                                        errorMessage: "年数和月数不能同时为空"
                                    }
                                ]
                            },
                            month: {
                                rules: [{
                                        required: true,
                                        errorMessage: '月份不能为空'
                                    },
                                    {
                                        format: 'number',
                                        errorMessage: '请输入有效月数'
                                    }, {
                                        validateFunction: (a, value) => {
                                            if (value > 12 || value < 1) {
                                                return false;
                                            }
                                            return true;
                                        },
                                        errorMessage: "月数范围为（1-12）"
                                    },
                                ]
                            }
                        }
                        break;
                }
                this.$refs.form.setRules({
                    ...this.rules,
                    ...newRules
                })
            })
        },
        methods: {
            appointmentRequiredChange(e) {
                this.formData.appointmentRequired = e.detail.value;
            },
            selectImage(files) {
                this.formData.imageFileList = files.tempFiles;
            },
            handleUploadSuccess(e) {
                const {
                    tempFilePaths,
                    tempFiles
                } = e
                this.formData.imageOrders = tempFiles.map(file => file.name)
                this.formData.retainImages = [...this.formData.retainImages, ...tempFilePaths]
            },
            handleImageDelete(file) {
                this.formData.retainImages = this.formData.retainImages.filter(
                    img => img !== file.tempFilePath
                )
                this.formData.imageOrders = this.formData.imageOrders.filter(
                    name => name !== file.name
                )
            },
            async submitForm() {
				console.log(this.formData)
            }
        },
        async onLoad(options) {
			
			
            this.categoryOptions = getProductCategory()
            const res = await getProductBrand()
            if (res.code >= 0) {
                this.brandOptions = res.data
            }
            const res2 = await getCarSuppliesCategory()
            if (res2.code >= 0) {
                this.carSuppliesCategoryOptions = res2.data
            }
            const res3 = await getCarServicesType()
            if (res3.code >= 0) {
                this.serviceTypes = res3.data
            }
            const res4 = await getVipPackageVip()
            if(res4.code>=0){
                this.vipOptions=res4.data
            }
			this.id=options.id;
			//查询单个商品
			const respo = await get_qcd_product({id:this.id})
			if (respo.code >= 0) {
			    this.formData={...respo.data,category:respo.data.productCategory,imageFileList:[],carSuppliesCategory:respo.data.category};
				var base_url="";
				switch(this.formData.category){
					case"sys_car_supplies":
					base_url="http://localhost:2303/Images/Product/CarSupplies/"+this.id;
					break;
					case"car_services":
					base_url="http://localhost:2303/Images/Product/CarServices/"+this.id;
				}
				var imageNames=this.formData.images.split(',');
				for(var key in imageNames){
					var imageName=imageNames[key];
					var extend=imageName.substring(imageName.lastIndexOf(".")+1)
					this.formData.imageFileList.push({
						url:base_url,
						extname:extend,
						name:imageName
					});
				}
				console.log(this.formData.imageFileList)
			}
			console.log(this.formData)
        },
        onShow: async () => {
            isLogin()
        }
    }
</script>

<style lang="scss" scoped>
    .container {
        padding: 24rpx 32rpx;
    }

    .form-row {
        display: flex;
        gap: 30rpx;

        .row-item {
            flex: 1;
        }
    }

    .submit-btn {
        margin-top: 40rpx;
        width: 100%;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 40rpx;
        background: #007AFF;
        color: white;
    }

    ::v-deep .uni-forms-item__label {
        font-weight: 500;
        color: #333;
    }
</style>